from flask import Flask, request, render_template, redirect, url_for, jsonify
from models import init_db, get_all_mabiao, get_mabiao_by_id, add_mabiao, update_mabiao, delete_mabiao, get_total_mabiao, get_paginated_mabiao, search_mabiao_by_keyword
import threading, webbrowser
from config import FIELD_NAMES

app = Flask(__name__, static_url_path='/static')

# 初始化数据库
init_db()
MAX_PAGE = 20


# 定义max和min函数
def max(a, b):
    return a if a > b else b


def min(a, b):
    return a if a < b else b


# 注册max和min函数到Jinja2模板环境
app.jinja_env.globals.update(max=max, min=min)


# @app.route('/')
# def index():
#     page = request.args.get('page', 1, type=int)
#     per_page = MAX_PAGE
#     offset = (page - 1) * per_page
#     total = get_total_mabiao()
#     rows = get_paginated_mabiao(page, per_page)
#     pagination = {
#         'total': total,
#         'current_page': page,
#         'per_page': per_page,
#         'total_pages': (total + per_page - 1) // per_page
#     }
#     return render_template('index.html', rows=rows, pagination=pagination)
@app.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    per_page = MAX_PAGE
    offset = (page - 1) * per_page

    # 获取总记录数和分页记录
    total = get_total_mabiao()
    rows = get_paginated_mabiao(page, per_page)

    # 处理字段为空的情况，将 None 替换为 ""
    rows = [{
        k: (v if v is not None else "")
        for k, v in row.items()
    } for row in rows]

    # 构建分页信息
    pagination = {
        'total': total,
        'current_page': page,
        'per_page': per_page,
        'total_pages': (total + per_page - 1) // per_page
    }

    # 渲染模板
    return render_template('index.html', rows=rows, pagination=pagination)


@app.route('/view/<int:id>')
def view(id):
    row = get_mabiao_by_id(id)
    if row:
        return render_template('view.html', row=row)
    else:
        return "Not found", 404


# @app.route('/edit/<int:id>', methods=['GET', 'POST'])
# def edit(id):
#     if request.method == 'POST':
#         data = request.form
#         update_mabiao(id=id,
#                       hanzi=data['hanzi'],
#                       quanma=data['quanma'],
#                       yima=data.get('yima'),
#                       erma=data.get('erma'),
#                       sanma=data.get('sanma'),
#                       sima=data.get('sima'),
#                       pinyin=data.get('pinyin'),
#                       danzi=int(data['danzi']))
#         return redirect(url_for('view', id=id))
#     else:
#         row = get_mabiao_by_id(id)
#         if row:
#             return render_template('edit.html', row=row)
#         else:
#             return "Not found", 404


@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
    if request.method == 'POST':
        data = request.form
        # 根据字段名称列表构建需要更新的字段字典
        fields = {field: data.get(field, None) for field in FIELD_NAMES}
        # 将 danzi 字段转换为整数
        try:
            fields['danzi'] = int(data.get('danzi', 0))
        except ValueError:
            fields['danzi'] = 0  # 或者返回错误提示
        fields['id'] = id
        update_mabiao(**fields)
        return redirect(url_for('view', id=id))
    else:
        row = get_mabiao_by_id(id)
        if row:
            return render_template('edit.html', row=row)
        else:
            return "Not found", 404


@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        data = request.form
        # 根据字段名称列表构建需要插入的字段字典
        fields = {field: data.get(field, None) for field in FIELD_NAMES}
        # 将 danzi 字段转换为整数，并且确保其他字段值为字符串
        fields['danzi'] = int(data.get('danzi', 0))

        # 调用 add_mabiao 函数，传入字段字典
        add_mabiao(**fields)
        return redirect(url_for('index'))
    else:
        return render_template('add.html')


@app.route('/delete/<int:id>')
def delete(id):
    delete_mabiao(id)
    return redirect(url_for('index'))


# 新增的搜索路由
@app.route('/search', methods=['POST'])
def search():
    keyword = request.form.get('keyword')
    page = request.form.get('page', 1, type=int)  # 当前页码，默认第1页
    per_page = request.form.get('per_page', MAX_PAGE, type=int)  # 每页显示条数，默认10条

    if keyword:
        # 获取所有匹配的搜索结果
        all_results = search_mabiao_by_keyword(keyword)
        total = len(all_results)  # 总结果数
        total_pages = (total + per_page - 1) // per_page  # 总页数

        # 根据当前页码和每页条数切片结果
        start = (page - 1) * per_page
        end = start + per_page
        paginated_results = all_results[start:end]

        # 替换字段中的 None 为 ""
        processed_results = [{
            k: (v if v is not None else "")
            for k, v in result.items()
        } for result in paginated_results]

        # 返回分页数据和结果
        return jsonify({
            'results': processed_results,
            'pagination': {
                'total': total,
                'current_page': page,
                'per_page': per_page,
                'total_pages': total_pages,
            }
        })

    # 如果没有提供关键词，返回空结果
    return jsonify({
        'results': [],
        'pagination': {
            'total': 0,
            'current_page': 1,
            'per_page': per_page,
            'total_pages': 0,
        }
    })


def open_browser():
    webbrowser.open('http://127.0.0.1:5000')


if __name__ == '__main__':
    # 创建并启动线程
    threading.Thread(target=open_browser).start()
    # 启动Flask应用
    app.run()
